<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>20组件自定义事件</title>
</head>
<body>
<div id="app">
    <!--把父组件的message绑定到子组件的parentMessage，父组件的message值修改后子组件的parentMessage值也会修改-->
    <!--v-on:child-event="parentFunc"不能写成parentFunc()-->
    <inner-button-counter01 v-bind:parent-message="message" v-on:child-event="parentFunc"></inner-button-counter01>
    <div>--------------------</div>
    <inner-button-counter02 v-bind:parent-message="message"></inner-button-counter02>
    文本插值输出父组件的属性值：{{message}}
</div>
<script src="../vue.global.3.0.5.js"></script>
<script>
    //创建局部组件(推荐)
    const innerButtonCounter01 = {
        data() {
            return { message: "子组件01" }
        },
        methods: {
            childClick(value) {
                //触发子组件的自定义事件，将一个子组件的数据传给父组件
                //this.$emit("child-event", value);
                //触发子组件的自定义事件，将多个子组件的数据传给父组件
                this.$emit("child-event", {value});
            }
        },
        //prop通信
        props: ["parentMessage"],
        //创建自定义事件，相当于click，触发子组件的自定义事件执行绑定的父组件的方法
        //emits: ['child-event'],
        //验证自定义事件
        emits: {
            'child-event': (value)=> {
                if(value != 'abc'){
                    return false;
                }
                else{
                    return true;
                }
            }
        },
        template: `
            {{ message }}
            <div>{{ parentMessage }}</div>
            <button v-on:click="childClick(message)">{{message}}</button>
        `
    }
    const innerButtonCounter02 = {
        data() {
            return { message: "子组件02" }
        },
        //prop通信
        props: ["parentMessage"],
        template: `
            {{ message }}
            <div>{{ parentMessage }}</div>
        `
    }

    //1、创建一个Vue应用实例，本身是最顶层的根组件
    const app = Vue.createApp({
        data() {
            return { message: "父组件message"}
        },
        methods: {
            parentFunc(value) {
                console.log(value);
                this.message = value.value;
            }
        },
        //定义一个局部组件，本组件是根组件的子组件(推荐)
        components: {
            "inner-button-counter01": innerButtonCounter01,
            "inner-button-counter02": innerButtonCounter02
        }
    });
    //2、定义一个全局组件
    app.component('button-counter', {
        //数据
        data() {
            return {counter: 100}
        },
        //模板
        template: `
            计算器: {{counter}}
            <button v-on:click="counter++">counter++</button><br>
        `   
    });
    //3、挂载
    const vm = app.mount("#app");
</script>
</body>
</html>